import React, {Component} from 'react';
import {UIManager} from 'NativeModules';
import LogService from "../../services/base/LogService";
import {Modal, TouchableOpacity} from "react-native";
import * as Animatable from 'react-native-animatable';
import PropTypes from 'prop-types';

/**
 * 下拉菜单
 */
export default class PopMenu extends Component {

  static propTypes = {
    width: PropTypes.number,  // 指定宽
    height: PropTypes.number, // 指定高
    bgColor: PropTypes.string,
  };

  constructor(props) {
    super(props);

    this.state = {
      visible: false,
      size: {
        x: 0,
        y: 0,
        width: 0,
        height: 0,
      }
    };
  }

  /**
   * 显示对话框
   * @param e
   */
  show = (e) => {

    // x、y:为视图的相对位置。width、height：为视图的宽度和高度。pageX、pageY为视图在屏幕上的绝对位置。
    UIManager.measure(e.target, (x, y, width, height, pageX, pageY) => {
      LogService.debug('相对位置', x, y);
      LogService.debug('绝对位置', pageX, pageY);

      this.setState({
        visible: true,
        size: {
          x: pageX,
          y: pageY + height,
          width: width,
          height: 200,
        }
      });
    });
  }

  /**
   * 隐藏对话框
   */
  dissmis = () => {

    this.anim['fadeOutUp'](300).then(endState => {
      this.setState({
        visible: false,
      });
    });
  }

  render() {

    let {x, y, width, height} = this.state.size;
    const {children, bgColor, h, w} = this.props;

    width = !!w ? w : width;
    height = !!h ? h : height;
    let bg = !!bgColor ? bgColor : 'rgba(0, 0, 0, 0.2)';

    return (
      <Modal
        // 动画类型  'none', 'slide', 'fade'
        animationType={"none"}
        transparent={true}
        visible={this.state.visible}
        // 显示完毕的回调方法 在 'Android' 平台，必需使用此函数
        onRequestClose={() => {
        }}
      >
        <TouchableOpacity
          activeOpacity={1}
          style={{flex: 1, backgroundColor: bg}}
          onPress={() => {
            this.dissmis();
          }}>
          <TouchableOpacity
            activeOpacity={1}
            style={{position: 'absolute', left: x, top: y, width, height}}
          >
            <Animatable.View
              animation="fadeInDown"
              duration={300}
              style={{flex: 1}}
              ref={(anim) => {
                this.anim = anim
              }}>
              {children}
            </Animatable.View>
          </TouchableOpacity>
        </TouchableOpacity>
      </Modal>
    );
  }
}